package com.meida.module.activity.provider.service.impl;

import com.meida.common.constants.CommonConstants;
import com.meida.common.mybatis.base.service.impl.BaseServiceImpl;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.model.ResultBody;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.mybatis.query.CriteriaSave;
import com.meida.common.mybatis.query.CriteriaUpdate;
import com.meida.common.security.OpenHelper;
import com.meida.common.base.utils.FlymeUtils;
import com.meida.module.activity.client.entity.InteActivity;
import com.meida.module.activity.provider.mapper.InteActivityMapper;
import com.meida.module.activity.provider.service.InteActivityService;
import com.meida.module.file.provider.service.SysFileService;
import com.meida.module.system.provider.service.SysAreaService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 周边活动 实现类
 *
 * @author flyme
 * @date 2019-10-06
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class InteActivityServiceImpl extends BaseServiceImpl<InteActivityMapper, InteActivity> implements InteActivityService {


    @Resource
    private SysAreaService areaService;

    @Resource
    private SysFileService fileService;

    @Override
    @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
    public ResultBody beforePageList(CriteriaQuery<InteActivity> cq, InteActivity activity, EntityMap requestMap) {
        //维度
        String lat = requestMap.get("lat");
        //经度
        String lon = requestMap.get("lon");
        //排序字段
        String order = requestMap.get("order");
        //排序方式
        String sort = requestMap.get("sort");
        cq.select(InteActivity.class, "*");
        cq.likeByField(InteActivity.class, "activityTitle");
        cq.select("shopType.typeName");
        if (FlymeUtils.allNotNull(lon, lat)) {
            //计算距离
            cq.addSelect("IFNULL(distance(" + lat + ", " + lon + ", lat, lon),0) distance");
            //设置排序
            if (FlymeUtils.isNotEmpty(order) && "distance".equals(order)) {
                cq.orderBy(order, sort);
            }
        }
        if (FlymeUtils.isNotEmpty(order)) {
            cq.orderBy(order, sort);
        } else {
            cq.orderByDesc("activity.recommend", "activity.createTime");
        }
        cq.likeByField(InteActivity.class, "activityTitle");
        cq.eq(InteActivity.class, "activityState");
        cq.eq(InteActivity.class, "typeId");
        cq.createJoin("com.meida.module.product.client.entity.ProdShopType");
        return ResultBody.ok();
    }


    @Override
    public List<EntityMap> listNearby(EntityMap params, int count, boolean collecon) {
        //维度
        String lat = params.get("lat");
        //经度
        String lon = params.get("lon");
        //排序字段
        String order = params.get("order");
        //排序方式
        String sort = params.get("sort");
        //是否推荐
        Integer recommend = params.getInt("recommend", null);
        CriteriaQuery cq = new CriteriaQuery(InteActivity.class);
        cq.select(InteActivity.class, "activityId", "activityTitle", "coverImage", "areaName", "viewCount", "activityTag", "activityAddress", "recommend");
        if (collecon) {
            setCollecon(cq);
        }
        if (FlymeUtils.allNotNull(lon, lat)) {
            cq.addSelect("IFNULL(distance(" + lat + ", " + lon + ", lat, lon),0) distance");
            if (FlymeUtils.isEmpty(order)) {
                //默认按距离正序排列
                cq.orderByAsc("distance");
            }

        }
        cq.eq("recommend", recommend);
        cq.eq(InteActivity.class, "activityState", CommonConstants.ENABLED);
        if (FlymeUtils.isNotEmpty(order)) {
            cq.orderBy(order, sort);
        }
        if (count > 0) {
            cq.last("limit " + count);
        }
        return selectEntityMap(cq);
    }

    @Override
    public ResultBody beforeAdd(CriteriaSave cs, InteActivity activity, EntityMap extra) {
        Long companyId = OpenHelper.getCompanyId();

        String lat = activity.getLat();
        String lon = activity.getLon();
        if (FlymeUtils.isEmpty(lat) || "undefined".equals(lat)) {
            activity.setLat("0");
        }
        if (FlymeUtils.isEmpty(lon) || "undefined".equals(lon)) {
            activity.setLon("0");
        }
        activity.setShopId(companyId);
        activity.setActivityState(CommonConstants.ENABLED);
        activity.setViewCount(0);
        activity.setRecommend(CommonConstants.DISABLED);
        activity.setAreaName(areaService.getAreaName(activity.getProId(), activity.getCityId(), activity.getAreaId()));
        return ResultBody.ok();
    }

    @Override
    public ResultBody beforeEdit(CriteriaUpdate<InteActivity> cu, InteActivity activity,EntityMap extra) {
        activity.setAreaName(areaService.getAreaName(activity.getProId(), activity.getCityId(), activity.getAreaId()));
        return ResultBody.ok();
    }

    @Override
    public void afterGet(CriteriaQuery cq, EntityMap result) {
        Long activityId = result.getLong("activityId");
        int viewCount = result.getInt("viewCount", 0) + 1;
        CriteriaUpdate cu = new CriteriaUpdate();
        cu.set("viewCount", viewCount);
        cu.eq(true, "activityId", activityId);
        result.put("viewCount", viewCount);
        //活动图片轮播图
        List<EntityMap> sliderImageList = fileService.selectFileListByFileType(activityId, InteActivity.class, "image");
        result.put("sliderImageList", sliderImageList);
        baseUpdate(cu);
    }

    private void setCollecon(CriteriaQuery<InteActivity> cq) {
        //是否添加收藏标记
        Long userId = OpenHelper.getUserId();
        if (FlymeUtils.isNotEmpty(userId)) {
            cq.addSelect("(select count(targetId) from sys_collecon sc where sc.targetId=activity.activityId and targetEntity='InteActivity' and userId=" + userId + ") colleconTag");
        }
    }
}
